<?php defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

/* JoomLeague League Management and Prediction Game for Joomla!
 * @version $Id: editevents.class.php 1126 2008-06-09 05:45:04Z julienv $
 * @package Joomleague
 * @copyright Copyright (C) 2007  JoomLeague
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see _joomleague_license.txt
 *  
 * Homepage: http://www.joomleague.de
 * Support: htt://www.joomleague.de/forum/
 * 
 * This file is part of JoomLeague.
 *  
 * JoomLeague is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * Please note that the GPL states that any headers in files and
 * Copyright notices as well as credits in headers, source files
 * and output (screens, prints, etc.) can not be removed.
 * You can extend them with your own credits, though...
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * The "GNU General Public License" (GPL) is available at
 * http://www.gnu.org/copyleft/gpl.html.
*/ 
class jl_EditEvents extends JoomLeague {
	
  var $project;
  
  var $match;
  
  var $matches;
  
  var $backend;
  
  function jl_EditEvents( &$project, &$match, $backend=false ) 
  {    
    $this->project = $project;
    $this->match = $match;
    $this->matches = array($match);
    $this->hometeam =  new JL_Team($this->project->_db);
    $this->hometeam->load($this->match->matchpart1);
    $this->awayteam =  new JL_Team($this->project->_db);
    $this->awayteam->load($this->match->matchpart2);
    $this->url = ($backend) ? 'index3.php?option=com_joomleague&no_html=1&amp;act' : JL_COMPONENT_LINK_NOHTML.'&func';
    if (!defined('JL_TEMPLATE_PATH')) define('JL_TEMPLATE_PATH', JL_FRONTEND_PATH.'/frontend/default');
    if (!defined('JL_TEMPLATE_FOLDERS_URL')) define('JL_TEMPLATE_FOLDERS_URL', JL_URL_FOLDER.'/frontend/default');
  }
  
  /**
   * return array of mosHTML::makeOption from specified team players
   * not already in specified array
   * 
   * @param int $team_id
   * @param bool $multiple
   * @param array $already_sel array of player ids
   * @return array of objects mosHTML::makeOption
   */
  function make_player_options ($team_id, $multiple=false, $already_sel=false) 
  {
    // get players info for list
  	$query = "SELECT pl.id, pl.firstname, pl.lastname, 
                     pos.name AS positionname
              FROM #__joomleague_players pl
              LEFT JOIN #__joomleague_playertool pt ON pl.id = pt.player_id
              LEFT JOIN #__joomleague_positions AS pos ON pos.id = pt.position_id
              WHERE pl.id = pt.player_id 
                AND team_id = '".$team_id."' 
                AND pt.project_id = '".$this->project->id."' ";
    if (is_array($already_sel) && count($already_sel) > 0) {
      $query .= " AND pl.id NOT IN (".implode(',', $already_sel).")"; 
    }
    $query .= " ORDER BY pos.ordering, pl.lastname";
        
		$this->project->_db->setQuery($query);
		$teamplayers = $this->project->_db->loadObjectList();

    $playeroptions = array();
    if (!$multiple)  $playeroptions[0] = _JL_ADMIN_SELECT_PLAYER;
    foreach($teamplayers as $result){
    	if ($multiple) $playeroptions[] = mosHTML::makeOption($result->id, jl_utf8_convert(sprintf("%s, %s (%s)", $result->lastname, $result->firstname, $result->positionname)));
    	else $playeroptions[$result->id] = jl_utf8_convert(sprintf("%s, %s", $result->lastname,$result->firstname));
    }
    if ($multiple) return $playeroptions;
    else $playeroptions[0] = _JL_ADMIN_SELECT_PLAYER;
    return $playeroptions;
  }

  function showEventsForm() 
  {
    $match = $this->match;
    $matches = $this->matches;
		$team1 = $this->hometeam;
    $team2 = $this->awayteam;
    
    $sortedevents=array();
    $eventtypeoptions[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_EVENT );
	
	  $eventtypes=$this->project->getEventTypes();
	  foreach ($eventtypes AS $eventtype) { 
	   $eventtypeoptions[] = mosHTML::makeOption( $eventtype->id, $eventtype->name ); 
	  }
    
    $homeoptions = $this->make_player_options($this->match->matchpart1);		
    $guestoptions = $this->make_player_options($this->match->matchpart2);
    
    $project_id = $this->project->id;
    $joomleague = $this->project;
    $mid = $this->match->match_id;
    require(getTemplateFile(JL_TEMPLATE_PATH,'/new_event.tpl.php'));
  }
    
	function showEventsNav () 
	{
	  $mid = $this->match->match_id;
	  $project_id = $this->project->id;
	  $joomleague = $this->project;
      $overall_config = $this->project->getTemplateConfig("overall.tpl");
	  require(getTemplateFile(JL_TEMPLATE_PATH,'/edit_event_nav.tpl.php'));
	}
    
  function showEvents($display) 
  {
	  $msg='';
	  $match = $this->match;
    $matches = $this->matches;
		$team1 = $this->hometeam;
    $team2 = $this->awayteam;
    $overall_config = $this->project->getTemplateConfig("overall.tpl");
    $events_required = (isset($overall_config['use_jl_events_required'])) ? $overall_config['use_jl_events_required'] : 0;
    
		$eventtypeoptions[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_EVENT );
		
		$eventtypes=$this->project->getEventTypes();
		
		foreach ($eventtypes AS $eventtype) {
		  $eventtypeoptions[] = mosHTML::makeOption( $eventtype->id, jl_utf8_convert($eventtype->name) ); 
	  }
		
		$sortedevents=array();
		
		$sortedevents = $this->project->jlmatchevents( $matches );
	
	  $homeoptions = $this->make_player_options($this->match->matchpart1);	  
	  $guestoptions = $this->make_player_options($this->match->matchpart2);
	
	  $project_id = $this->project->id;
	  $joomleague = $this->project;
	  $mid = $this->match->match_id;
	  
    require(getTemplateFile(JL_TEMPLATE_PATH, 'new_event.tpl.php'));
		require(getTemplateFile(JL_TEMPLATE_PATH, 'edit_match_events.tpl.php'));		
	}
	    
	function jl_editMessage($msg) {
	  ?>
	  <script type="text/javascript"> document.getElementById('log_res').innerHTML = '<?php echo addslashes($msg);?>';</script>
	  <?php
	}
	
	function editSquad() 
	{
	  $team = intval(mosGetParam($_REQUEST, 'team', 0));
	  
	  // get team name
	  $query = "SELECT name FROM #__joomleague_teams WHERE id = '".$team."'";
	  $this->project->_db->setQuery($query);
	  $teamname = $this->project->_db->loadResult();
	
	  $positions = $this->project->getPositions();
	  
	  $allplayers = $this->match->getRoster($team);
	  // generate position list for selection box
	  $poslist[] = mosHTML::makeOption('0', jl_utf8_convert(_JL_PLAYER_POSITION));
	  
	  $post_add = '';
	  $squad = array();
	  // generate selection list for each position
	  foreach ($positions AS $key=>$pos) {
	  // get players assigned to this position
	   $squad[$key] = $this->match->getRoster($team, $key);
	   $poslist[] = mosHTML::makeOption($key, jl_utf8_convert($pos->name));
	   $post_add .= "selectAll(document.getElementById('sqad".$key."'));";
	  }
	  if (count($squad) > 0) {
		  foreach ($squad AS $key=>$players) {
		    $x=0;
		    $temp[$key] = array();
		    foreach($players AS $player) {
			    $options[$key][$x]->value = $player;
			    $p = new Player($this->project->_db);
			    $p->load($player);
			    $options[$key][$x]->text = jl_utf8_convert($p->lastname.', '.$p->firstname.' ('.$positions[$key]->name.')');
			    $temp[$key][$x]->value = $player;
			    $x++;
		    }
		  }
	  }
	  // get options of not assigned players
	  $squadoptions = $this->make_player_options($team, 1, $allplayers);
	  // get players from team
	  $in_out_options = $this->make_player_options($team); //should be changed to another function
	  $came_in = $this->match->getSubstitutes($this->project->id);
	  require(getTemplateFile( JL_TEMPLATE_PATH,'/edit_squad.tpl.php') );
	}
	
	function saveMatchEvent () 
  {	
	  $event_time   = mosGetParam( $_REQUEST, "event_time", '' );
		$player_id    = intval( mosGetParam( $_REQUEST, "player_id", 0 ) );
		$player_id2   = intval( mosGetParam( $_REQUEST, "player_id2", 0 ) );
		$team_id      = intval( mosGetParam( $_REQUEST, "team_id", 0 ) );
		$notice       = mosGetParam( $_REQUEST, "notice", '');
		$eventtype    = intval(mosGetParam( $_REQUEST, "event_type_id", 0 ) );
		$event_sum    = intval(mosGetParam( $_REQUEST, "event_sum",1 ) );
		if ( function_exists('iconv') ) {
		  $notice = iconv(_JL_ENCODING, 'UTF-8', $notice);
		}
		
		if ( $player_id && $eventtype && $team_id ) 
		{
			$query="INSERT INTO #__joomleague_match_events (match_id, player_id, player_id2, team_id, event_time, event_type_id, event_sum, project_id, notice)
		      		VALUES ('".$this->match->match_id."', '$player_id', '$player_id2', $team_id, '$event_time', '$eventtype', '$event_sum', '".$this->project->id."', '$notice')";
			$this->project->_db->setQuery($query);
			$this->project->_db->query();
			$msg = "<span style='color:#00ff00;'><b>EVENT HAS BEEN SAVED!!</b></span>";
	  }
	  else {
	    $msg = "<span style='color:#ff0000;'><b>NO PLAYER AND / OR EVENT HAS BEEN SENT!!</b></span>";
    }
    return $msg;
	}
	
	function deleteMatchEvent() {
	
	  $event_id=intval(mosGetParam($_REQUEST, "evid",'0'));
		if($event_id!=0) {
		  $query="DELETE FROM #__joomleague_match_events WHERE event_id = '$event_id'";
	    $this->project->_db->setQuery($query);
	    $this->project->_db->query();
	    $msg = "<span style='color:#00ff00;'><b>EVENT DELETED</b></span>";
	  }
	  else $msg = "<span style='color:#ff0000;'><b>DELETE EVENT - NO PLAYER AND / OR EVENT HAS BEEN SENT!!</b></span>";
	  
	}
	function updateMatchEvent() {
	
	  $event_id=intval(mosGetParam($_REQUEST, "evid",0));
	  $event_sum=intval(mosGetParam($_REQUEST, "event_sum",1));
	  $event_time=mosGetParam($_REQUEST, "event_time",'');
	  if ($event_time=="") $event_time="NULL";
	  $player_id=intval(mosGetParam($_REQUEST, "player_id",0));
	  $player_id2=intval(mosGetParam($_REQUEST, "player_id2",0));
	  $notice=mosGetParam($_REQUEST, "notice",'');
	  if (function_exists('iconv')){
		  $notice = iconv('UTF-8', _JL_ENCODING, $notice);
		}
	  $eventtype=intval(mosGetParam($_REQUEST, "event_type_id",0));
	  
		if ($player_id!=0&&$eventtype!=0&&$event_id!=0) {
	    $query = "UPDATE #__joomleague_match_events SET player_id = '$player_id', player_id2 = '$player_id2', event_time = '$event_time', notice = '$notice',
	            event_type_id = '$eventtype', event_sum = '$event_sum' WHERE event_id = '$event_id'";
	    $this->project->_db->setQuery($query);
	    if (!$this->project->_db->query()) {
	      $msg = "<span style='color:#ff0000;'><b>ERROR SAVING DATA</b><br /></span>";
	    }
	    else $msg =  "<span style='color:#00ff00;'><b>DATA HAS BEEN UPDATED SUCCESSFULLY</b><br /></span>";
	  }
	  else $msg = "<span style='color:#ff0000;'><b>YOU CAN NOT SET PLAYER AND / OR EVENTTYPE TO EMPTY VALUES!</b><br /></span>";
	
	}

  function saveSquad() 
  {
      $team = intval(mosGetParam($_REQUEST, "team", 0));
    	// update starting roster
	    $positions = $this->project->getPositions();
	    $assigneds = $this->match->getRoster($team); //return currently saved starter list
      $squad = array();
      $sorted = array();
	    
	    // get all players assigned from the position boxes 
	    foreach ($positions AS $key=>$pos) 
	    {
	      $sended = mosGetParam($_REQUEST, "sqad".$key,array());
	      for ($x=0;$x<count($sended);$x++) {
	        $squad[]=$sended[$x];
	        $sorted[$key][] = $sended[$x];
	      }
	    }
	    
	    // get difference bewteen saved roster and new roster list, and update the table accordingly 
	    $to_delete = array_diff($assigneds,$squad);
	    if (count($to_delete) > 0) {
	      foreach ($to_delete AS $delete) {
	        $query = "DELETE FROM #__joomleague_match_players WHERE
	                match_id = '".$this->match->match_id."' AND player_id = '".$delete."' 
	                AND came_in = 0";
	        $this->project->_db->setQuery($query);
	        $this->project->_db->query();
	      }
	    }
	    
	    // update starting roster entries
	    if (count($sorted) > 0) {
	      foreach ($sorted AS $pos=>$pl) {
	        for ($x=0;$x<count($pl);$x++) {
	          if (in_array($pl[$x], $assigneds)) {
	            $query="UPDATE #__joomleague_match_players SET position_id = '".$pos."', ordering='$x' WHERE
	                match_id = '".$this->match->match_id."' AND player_id = '".$pl[$x]."' 
	                AND came_in = 0";
	          }
	          else {
	            $query = "INSERT IGNORE INTO #__joomleague_match_players (player_id, match_id, team_id, position_id, ordering)
	              VALUES ('".$pl[$x]."', '".$this->match->match_id."', '".$team."', '".$pos."', $x)";
	          }
	          $this->project->_db->setQuery($query);
	          $this->project->_db->query();
	        }
	      }
	    }
	}
	
  function updateSubst() 
  {
    $player_in = intval(mosGetParam($_REQUEST, "player_in", 0));
    $player_out = intval(mosGetParam($_REQUEST, "player_out", 0));
    $team = intval(mosGetParam($_REQUEST, "team", 0));
    $delSubst = intval(mosGetParam($_REQUEST, "delete", 0));
    
    if ($delSubst > 0 && $player_in > 0 && $player_out > 0) 
    {
      // delete a substitution
      // the starter is not going out any more
      $query = "UPDATE #__joomleague_match_players SET `out` = 0, in_out_time = null
                WHERE match_id = '".$this->match->match_id."' 
                  AND player_id = '".$player_out."' 
                  AND team_id = '".$team."'";
      $this->project->_db->setQuery($query);
      $this->project->_db->query();
      
      // the subsitute isn't getting in
      $query = "DELETE FROM #__joomleague_match_players WHERE id = '".$delSubst."'";
      $this->project->_db->setQuery($query);
      $this->project->_db->query();
    }
    else if ($player_in > 0 && $player_out > 0) 
    {
      // new substitution
      $in_out_time = intval(mosGetParam($_REQUEST, "in_out_time", 0));
      $position = intval(mosGetParam($_REQUEST, "position_id", 0));
      
      if ($position == 0) 
      {
        // retrieve normal position of player getting in
        $query = "SELECT position_id FROM #__joomleague_playertool 
                  WHERE project_id ='".$this->project->id
                ."' AND player_id ='".$player_in."' 
                    AND team_id ='".$team."'";
        $this->project->_db->setQuery($query);
        $position = $this->project->_db->loadResult();
      }
      
      // update starter entry with substitution info
      $query = "UPDATE #__joomleague_match_players SET `out` = 1, in_out_time = '".$in_out_time."'
      WHERE match_id = '".$this->match->match_id."' AND player_id = '".$player_out."'";
      $this->project->_db->setQuery($query);
      if (!$this->project->_db->query()) {
        //echo $this->project->_db->getQuery();
        //echo $this->project->_db->getErrorMsg();
      }
      
      // insert an entry for the substitute
      $query = "INSERT IGNORE INTO #__joomleague_match_players (team_id, match_id, player_id, came_in, in_for, in_out_time, position_id)
      VALUES ('".$team."', '".$this->match->match_id."', '".$player_in."', 1, '".$player_out."', '".$in_out_time."', '".$position."')";
      $this->project->_db->setQuery($query);
      $this->project->_db->query();
    }
  }

	function substitutionForm (&$players) {
	  $in_out = '';
	  for ($x=0;$x < count($players); $x++) 
	  {
	    ?>
	    <form id="delSubstitution<?php echo $players[$x]->id; ?>" 
	          name="delSubstitution<?php echo $players[$x]->id; ?>" 
            style="border:solid 1px;padding:4px;margin:4px;"
            action="javascript: jl_PostForm( serializeLineupForm(document.getElementById('delSubstitution<?php echo $players[$x]->id; ?>')), 'editarea');"
            enctype="application/x-www-form-urlencoded">
	    <input type="hidden" name="mid" value="<?php echo $this->match->match_id; ?>" />
			<input type="hidden" name="mytask" value="updatesubst" />
			<input type="hidden" name="func" id="func" value="editEvents" />
			<input type="hidden" name="act" id="act" value="editEvents" />
			<input type="hidden" name="p" id="p" value="<?php echo $this->project->id; ?>" />
			<input type="hidden" name="player_in" id="player_in" value="<?php echo $players[$x]->player_id; ?>" />
			<input type="hidden" name="player_out" id="player_out" value="<?php echo $players[$x]->in_for; ?>" />
			<input type="hidden" name="team" id="team" value="<?php echo $players[$x]->team_id; ?>" />
			<input type="hidden" name="option" id="option" value="com_joomleague" />
			<input type="hidden" name="no_html" id="no_html" value="1" />
	    <?php
    if ($players[$x]->in_for) 
    {
       echo ' <img src="'.JL_TEMPLATE_FOLDERS_URL.'/images/out.png" alt="ausgewechselt" /> ';
       echo  jl_utf8_convert($players[$x]->out_lastname);
       if ($players[$x]->out_firstname != '') {
        echo ', '.jl_utf8_convert(substr($players[$x]->out_firstname, 0,1)).'.';
       }
    }
    echo '<img src="'.JL_TEMPLATE_FOLDERS_URL.'/images/in.png" alt="eingewechselt" /> ';
    
    echo jl_utf8_convert($players[$x]->lastname);
    if ($players[$x]->firstname != '') echo ', '.jl_utf8_convert(substr($players[$x]->firstname, 0,1)).'.';
    $query = "SELECT name FROM #__joomleague_positions WHERE id ='".$players[$x]->position_id."'";
        $this->project->_db->setQuery($query);
        $position = $this->project->_db->loadResult();
    echo ' ('.$position.')';
    $time = (!is_null($players[$x]->in_out_time) && $players[$x]->in_out_time > 0) ? $players[$x]->in_out_time : '--';
    echo  ' ('.$time.'. Min.) ';
    echo '<input type="submit" value="DEL" class="inputbox" />
    <input type="hidden" name="delete" id="delete" value="'.$players[$x]->id.'" />
    </form>';
  }
	}
}